﻿using ConfigInfoWebPlatform.API.BusinessCommon;
using ConfigInfoWebPlatform.API.DBCommon;
using ConfigInfoWebPlatform.Model;
using ConfigInfoWebPlatform.Model.Model;
using ConfigInfoWebPlatform.Nlog;
using FileSecretAssemblyStandard;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConfigInfoWebPlatform.API.Controllers
{
    /// <summary>
    /// 案件要素中心结构配置
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class CasetypeStructConfigController : ControllerBase
    {
        readonly LogHelper _log;
        readonly string configRootPath;
        readonly string initDB;
        readonly InterfaceFileSecret FileSecret;
        /// <summary>
        /// 案件要素中心结构配置控制器
        /// </summary>
        /// <param name="logHelper"></param>
        /// <param name="configuration"></param>
        /// <param name="fileSecret"></param>
        public CasetypeStructConfigController(LogHelper logHelper, IConfiguration configuration, InterfaceFileSecret fileSecret)
        {
            _log = logHelper;
            configRootPath = configuration["AppSetting:configPath"].ToString();
            initDB = configuration["AppSetting:initDB"].ToString();
            FileSecret = fileSecret;
        }

        /// <summary>
        /// Index
        /// </summary>
        /// <param name="dir">首页</param>
        /// <param name="page">首页</param>
        /// <param name="limit">首页</param>
        /// <returns></returns>
        // GET: Manager/CaseElementCfgFile
        [HttpGet("index")]
        public JsonResult Index(string dir, int page, int limit)
        {
            var fname = Request.Query["fname"];
            //获取用户信息
            UserInfoModel user = new UserInfoModel();
            var userJsonStr = Base64Helper.DeCodeBase64(65001, Request.Headers["user"]);
            user = Newtonsoft.Json.JsonConvert.DeserializeObject<UserInfoModel>(userJsonStr);
            //获取用户角色操作权限
            DAL_Role dal_Role = new DAL_Role();
            var isOperate = dal_Role.GetOperateAuthorityByRid(user.R_id);
            //获取版本信息
            VersionModel version = new VersionModel();
            var versionJsonStr = Base64Helper.DeCodeBase64(65001, Request.Headers["version"]);
            version = Newtonsoft.Json.JsonConvert.DeserializeObject<VersionModel>(versionJsonStr);
            var versionPath = version?.Catalogue == "dev"
                                ? ""
                                : version?.Catalogue;
            string filepath = Path.Combine(configRootPath, versionPath, dir).Replace("\\", "/");
            if (!Directory.Exists(filepath))
            {
                Directory.CreateDirectory(filepath);
            }
            // 获取流程配置的文件结构
            DAL_ConfigFile configFile = new DAL_ConfigFile();
            List<ConfigFileInfoModel>  caseElementCfgFileInfos = configFile.GetConfigFiles(dir);

            var configFileList = (from file in caseElementCfgFileInfos
                                 group file by new { file.name, file.path } into temp
                                 let time = temp.Max(g => g.createdTime)
                                 from list in temp
                                 where list.createdTime == time
                                 select list).ToList();

            if (!string.IsNullOrWhiteSpace(fname))
                configFileList = configFileList.Where(x => x.name.Contains(fname)).ToList();

            List<ConfigFileInfoModel> re = new List<ConfigFileInfoModel>();
            // 获取页面的数据
            if (configFileList != null && configFileList.Count > 0)
            {
                re = configFileList.Skip((page - 1) * limit).Take(limit).ToList();
            }
            return new JsonResult(new { code = 0, msg = "成功", count = configFileList.Count(), isOperate = user.Name == "admin" ? 1 : isOperate, data = re });
        }

        /// <summary>
        /// 查看文件内容
        /// </summary>
        /// <param name="fileName">文件名称</param>
        /// <returns></returns>
        [HttpGet("detail")]
        public ActionResult Detail(string fileName)
        {
            string fileContent = "";
            try
            {
                //获取版本信息
                VersionModel version = new VersionModel();
                var versionJsonStr = Base64Helper.DeCodeBase64(65001, Request.Headers["version"]);
                version = Newtonsoft.Json.JsonConvert.DeserializeObject<VersionModel>(versionJsonStr);
                var versionPath = version?.Catalogue == "dev"
                                    ? ""
                                    : version?.Catalogue;
                string filenametemp = Path.Combine(configRootPath,versionPath, fileName);
                fileContent = FileSecret.DecryptFileToContent(filenametemp);
                return new JsonResult(fileContent);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }

        }
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns></returns>
        [HttpGet("downloadfile")]
        public ActionResult DownLoadFile(string fileName)
        {
            //获取版本信息
            VersionModel version = new VersionModel();
            var versionJsonStr = Base64Helper.DeCodeBase64(65001, Request.Headers["version"]);
            version = Newtonsoft.Json.JsonConvert.DeserializeObject<VersionModel>(versionJsonStr);
            var versionPath = version?.Catalogue == "dev"
                                ? ""
                                : version?.Catalogue;
            Result re = new Result();
            if (!string.IsNullOrEmpty(fileName))
            {
                re.code = "1";
                string filenameTemp = Path.Combine(configRootPath, versionPath, fileName);
                string clientFileName = Path.GetFileName(fileName);
                string fileContent = FileSecret.DecryptFileToContent(filenameTemp);
                byte[] bytes = Encoding.UTF8.GetBytes(fileContent);
                //二进制流数据（如常见的文件下载）
                return File(bytes, "application/octet-stream", clientFileName);
            }
            else
            {
                re.code = "0";
                re.message = "下载失败";
                return BadRequest(re);
            }
        }


    }
}
